package com.loveyukari.controller;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.loveyukari.support.JsonResult;

/**
 *
 * yangshaohua 2017年1月27日上午2:19:31
 **/

@RequestMapping("/douyu/find")
@Controller
public class FindChatmsgController {
	private Logger log = LoggerFactory.getLogger(FindChatmsgController.class);

	@RequestMapping(value="/chatmsg")
	@ResponseBody
	public JsonResult<String> findChatmsg(String name,String dateStr) {
		if (StringUtils.isBlank(name)) {
			return new JsonResult<String>(0,"","");
		}
		StringBuilder sbResult = new StringBuilder();
		String shell = "cat /var/log/yukari/yukari_room_talk.log | grep 'chatmsg' | grep '" + name + "'";
		try {
			Process process = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", shell });
			if (process.waitFor() == 0) {
				String logStr = getInputStream(process.getInputStream());
				String[] chatmsgs = logStr.split("\n");
				for (int i = 0; i < chatmsgs.length; i++) {
					String chatmsg = chatmsgs[i];
					try {
						String[] split = chatmsg.split(" - ");
						String msg = split[1];
						msg = msg.replace("/", "").replace("=,", "=\"\",");
						JSONObject msgJson = new JSONObject(msg);
						String nn = msgJson.getString("nn");
						if (nn.contains(name)) {
							String timeStr = split[0].substring(0, 21);
							sbResult.append(timeStr).append(nn).append(": ").append(msgJson.getString("txt")).append("\r\n");
						}
					} catch (JSONException e) {
						log.error(chatmsg, e);
					}
				}
			} else {
				String logStr = getInputStream(process.getErrorStream());
				log.error(logStr);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return new JsonResult<String>(0,"",sbResult.toString());
	}
	
	
	
	private String getInputStream(InputStream inputStream) throws IOException{
		byte[] bs = new byte[1024];
		StringBuilder sb = new StringBuilder();
		while (true) {
			int readLength = inputStream.read(bs, 0, bs.length);
			if (readLength == -1) {
				break;
			}
			sb.append(new String(bs, 0, readLength));
		}
		return sb.toString();
	}
}
